import {
  SET_OPEN_TYPE,
  SET_SELECT_VALUE,
  SET_TITLE_VALUE,
  SET_FILTER_DATA
} from '../actionTypes/filtersActionTypes'

const initialState = {
  openType: '', // 打开类型
  selectTitleValue: {
    // 标题选中状态
    area: false,
    mode: false,
    price: false,
    more: false
  },
  selectValue: {
    // 选中的值
    area: ['area', 'null'],
    mode: ['null'],
    price: ['null'],
    more: []
  },
  filterData: {} // 筛选数据
}

export default (state = initialState, action) => {
  switch (action.type) {
    // 设置openType
    case SET_OPEN_TYPE:
      const newState1 = { ...state }

      // 设置openType
      newState1.openType = action.payload

      // 处理选中状态
      Object.keys(newState1.selectTitleValue).forEach(key => {
        if (key === 'area') {
          newState1.selectTitleValue[key] =
            newState1.selectValue[key].length > 2
        } else if (key === 'mode') {
          newState1.selectTitleValue[key] =
            newState1.selectValue[key][0] !== 'null'
        } else if (key === 'price') {
          newState1.selectTitleValue[key] =
            newState1.selectValue[key][0] !== 'null'
        } else if (key === 'more') {
          newState1.selectTitleValue[key] =
            newState1.selectValue[key].length > 0
        }
      })

      return newState1

    // 设置选中的值
    case SET_SELECT_VALUE:
      const newState2 = { ...state }
      newState2.selectValue = { ...newState2.selectValue, ...action.payload }

      // 处理选中状态
      Object.keys(newState2.selectTitleValue).forEach(key => {
        if (key === 'area') {
          newState2.selectTitleValue[key] =
            newState2.selectValue[key].length > 2
        } else if (key === 'mode') {
          newState2.selectTitleValue[key] =
            newState2.selectValue[key][0] !== 'null'
        } else if (key === 'price') {
          newState2.selectTitleValue[key] =
            newState2.selectValue[key][0] !== 'null'
        } else if (key === 'more') {
          newState2.selectTitleValue[key] =
            newState2.selectValue[key].length > 0
        }
      })

      // 关闭窗口
      newState2.openType = ''

      return newState2

    // 设置标题选中的值
    case SET_TITLE_VALUE:
      const newState3 = { ...state }
      newState3.selectTitleValue = {
        ...newState3.selectTitleValue,
        ...action.payload
      }
      return newState3

    // 设置过滤的值
    case SET_FILTER_DATA:
      const newState4 = { ...state }
      newState4.filterData = action.payload
      return newState4

    default:
      return state
  }
}
